class OptionsManager {
  constructor() {
    this.settings = {};
    this.sessions = [];
    this.proxies = [];
    this.currentEditingSession = null;
    this.init();
  }

  async init() {
    await this.loadSettings();
    await this.loadSessions();
    await this.loadProxies();
    this.setupEventListeners();
    this.updateUI();
  }

  async loadSettings() {
    try {
      const response = await chrome.storage.local.get(['settings']);
      this.settings = response.settings || this.getDefaultSettings();
    } catch (error) {
      console.error('Failed to load settings:', error);
      this.settings = this.getDefaultSettings();
    }
  }

  async loadSessions() {
    try {
      const response = await chrome.runtime.sendMessage({ action: 'getSessions' });
      if (response.success) {
        this.sessions = response.sessions;
      }
    } catch (error) {
      console.error('Failed to load sessions:', error);
    }
  }

  async loadProxies() {
    try {
      const response = await chrome.storage.local.get(['proxies']);
      this.proxies = response.proxies || [];
    } catch (error) {
      console.error('Failed to load proxies:', error);
    }
  }

  getDefaultSettings() {
    return {
      autoSwitchSession: true,
      showSessionIndicator: true,
      enableNotifications: true,
      defaultSessionName: 'Session {number}',
      defaultFingerprintProtection: 'basic',
      enableGlobalProxy: false,
      protectCanvas: true,
      protectWebGL: true,
      protectAudio: true,
      blockWebRTC: true,
      userAgentMode: 'default',
      customUserAgent: '',
      maxSessions: 10,
      sessionTimeout: 0,
      enableDebugMode: false,
      clearDataOnClose: false,
      autoBackup: true
    };
  }

  setupEventListeners() {
    // Tab navigation
    document.querySelectorAll('.nav-tab').forEach(tab => {
      tab.addEventListener('click', () => this.switchTab(tab.dataset.tab));
    });

    // Save settings
    document.getElementById('saveBtn').addEventListener('click', () => this.saveSettings());

    // Import/Export
    document.getElementById('importBtn').addEventListener('click', () => this.importSessions());
    document.getElementById('exportBtn').addEventListener('click', () => this.exportSessions());

    // Session management
    document.getElementById('newSessionBtn').addEventListener('click', () => this.showSessionModal());

    // Proxy management
    document.getElementById('addProxyBtn').addEventListener('click', () => this.showProxyModal());

    // User agent mode change
    document.getElementById('userAgentMode').addEventListener('change', (e) => {
      const customGroup = document.getElementById('customUserAgentGroup');
      customGroup.style.display = e.target.value === 'custom' ? 'block' : 'none';
    });

    // Modal controls
    this.setupModalEventListeners();

    // Advanced actions
    document.getElementById('clearAllDataBtn').addEventListener('click', () => this.clearAllData());
    document.getElementById('createBackupBtn').addEventListener('click', () => this.createBackup());
    document.getElementById('restoreBackupBtn').addEventListener('click', () => this.restoreBackup());

    // Proxy test
    document.getElementById('testProxyBtn').addEventListener('click', () => this.testProxy());
  }

  setupModalEventListeners() {
    // Session modal
    document.getElementById('sessionModalClose').addEventListener('click', () => this.hideModal('sessionModal'));
    document.getElementById('sessionModalCancel').addEventListener('click', () => this.hideModal('sessionModal'));
    document.getElementById('sessionForm').addEventListener('submit', (e) => {
      e.preventDefault();
      this.saveSession();
    });

    // Proxy modal
    document.getElementById('proxyModalClose').addEventListener('click', () => this.hideModal('proxyModal'));
    document.getElementById('proxyModalCancel').addEventListener('click', () => this.hideModal('proxyModal'));
    document.getElementById('proxyForm').addEventListener('submit', (e) => {
      e.preventDefault();
      this.saveProxy();
    });

    // Proxy toggle in session modal
    document.getElementById('sessionEnableProxy').addEventListener('change', (e) => {
      const proxyConfig = document.getElementById('sessionProxyConfig');
      proxyConfig.style.display = e.target.checked ? 'block' : 'none';
    });
  }

  switchTab(tabName) {
    // Update nav tabs
    document.querySelectorAll('.nav-tab').forEach(tab => {
      tab.classList.remove('active');
    });
    document.querySelector(`[data-tab="${tabName}"]`).classList.add('active');

    // Update content
    document.querySelectorAll('.tab-content').forEach(content => {
      content.classList.remove('active');
    });
    document.getElementById(tabName).classList.add('active');
  }

  updateUI() {
    this.updateSettingsForm();
    this.updateSessionsGrid();
    this.updateProxyList();
  }

  updateSettingsForm() {
    // General settings
    document.getElementById('autoSwitchSession').checked = this.settings.autoSwitchSession;
    document.getElementById('showSessionIndicator').checked = this.settings.showSessionIndicator;
    document.getElementById('enableNotifications').checked = this.settings.enableNotifications;
    document.getElementById('defaultSessionName').value = this.settings.defaultSessionName;
    document.getElementById('defaultFingerprintProtection').value = this.settings.defaultFingerprintProtection;

    // Proxy settings
    document.getElementById('enableGlobalProxy').checked = this.settings.enableGlobalProxy;

    // Fingerprint settings
    document.getElementById('protectCanvas').checked = this.settings.protectCanvas;
    document.getElementById('protectWebGL').checked = this.settings.protectWebGL;
    document.getElementById('protectAudio').checked = this.settings.protectAudio;
    document.getElementById('blockWebRTC').checked = this.settings.blockWebRTC;
    document.getElementById('userAgentMode').value = this.settings.userAgentMode;
    document.getElementById('customUserAgent').value = this.settings.customUserAgent;

    // Show/hide custom user agent
    const customGroup = document.getElementById('customUserAgentGroup');
    customGroup.style.display = this.settings.userAgentMode === 'custom' ? 'block' : 'none';

    // Advanced settings
    document.getElementById('maxSessions').value = this.settings.maxSessions;
    document.getElementById('sessionTimeout').value = this.settings.sessionTimeout;
    document.getElementById('enableDebugMode').checked = this.settings.enableDebugMode;
    document.getElementById('clearDataOnClose').checked = this.settings.clearDataOnClose;
    document.getElementById('autoBackup').checked = this.settings.autoBackup;
  }

  updateSessionsGrid() {
    const grid = document.getElementById('sessionsGrid');
    grid.innerHTML = '';

    if (this.sessions.length === 0) {
      grid.innerHTML = `
        <div class="empty-state">
          <h3>No Sessions Created</h3>
          <p>Create your first session to get started with multi-account management.</p>
          <button class="btn primary" onclick="optionsManager.showSessionModal()">Create Session</button>
        </div>
      `;
      return;
    }

    this.sessions.forEach(session => {
      const sessionCard = this.createSessionCard(session);
      grid.appendChild(sessionCard);
    });
  }

  createSessionCard(session) {
    const card = document.createElement('div');
    card.className = 'session-card';
    
    const features = [];
    if (session.proxy && session.proxy.enabled) features.push('<span class="feature-tag proxy">Proxy</span>');
    if (session.fingerprintProtection) features.push('<span class="feature-tag fingerprint">Fingerprint</span>');
    if (session.userAgent) features.push('<span class="feature-tag">Custom UA</span>');

    card.innerHTML = `
      <div class="session-card-header">
        <div class="session-card-info">
          <div class="session-card-color" style="background-color: ${session.color}"></div>
          <div class="session-card-name">${session.name}</div>
        </div>
        <div class="session-card-actions">
          <button class="session-card-action" onclick="optionsManager.editSession('${session.id}')" title="Edit">
            <svg width="16" height="16" viewBox="0 0 24 24" fill="currentColor">
              <path d="M3 17.25V21h3.75L17.81 9.94l-3.75-3.75L3 17.25zM20.71 7.04c.39-.39.39-1.02 0-1.41l-2.34-2.34c-.39-.39-1.02-.39-1.41 0l-1.83 1.83 3.75 3.75 1.83-1.83z"/>
            </svg>
          </button>
          <button class="session-card-action danger" onclick="optionsManager.deleteSession('${session.id}')" title="Delete">
            <svg width="16" height="16" viewBox="0 0 24 24" fill="currentColor">
              <path d="M6 19c0 1.1.9 2 2 2h8c1.1 0 2-.9 2-2V7H6v12zM19 4h-3.5l-1-1h-5l-1 1H5v2h14V4z"/>
            </svg>
          </button>
        </div>
      </div>
      <div class="session-card-meta">
        <div class="session-card-stat">
          <div class="session-card-stat-value">${session.tabs.length}</div>
          <div class="session-card-stat-label">Tabs</div>
        </div>
        <div class="session-card-stat">
          <div class="session-card-stat-value">${this.formatDate(session.lastUsed)}</div>
          <div class="session-card-stat-label">Last Used</div>
        </div>
      </div>
      <div class="session-card-features">
        ${features.join('')}
      </div>
    `;

    return card;
  }

  updateProxyList() {
    const proxyItems = document.getElementById('proxyItems');
    proxyItems.innerHTML = '';

    if (this.proxies.length === 0) {
      proxyItems.innerHTML = `
        <div class="empty-state">
          <p>No proxy configurations saved</p>
        </div>
      `;
      return;
    }

    this.proxies.forEach((proxy, index) => {
      const proxyItem = document.createElement('div');
      proxyItem.className = 'proxy-item';
      proxyItem.innerHTML = `
        <div class="proxy-item-info">
          <div class="proxy-item-name">${proxy.name}</div>
          <div class="proxy-item-details">${proxy.type.toUpperCase()} ${proxy.host}:${proxy.port}</div>
        </div>
        <div class="proxy-item-actions">
          <button class="proxy-item-action" onclick="optionsManager.editProxy(${index})">Edit</button>
          <button class="proxy-item-action danger" onclick="optionsManager.deleteProxy(${index})">Delete</button>
        </div>
      `;
      proxyItems.appendChild(proxyItem);
    });
  }

  showSessionModal(sessionId = null) {
    this.currentEditingSession = sessionId;
    const modal = document.getElementById('sessionModal');
    const title = document.getElementById('sessionModalTitle');
    
    if (sessionId) {
      title.textContent = 'Edit Session';
      const session = this.sessions.find(s => s.id === sessionId);
      this.populateSessionForm(session);
    } else {
      title.textContent = 'Create New Session';
      this.clearSessionForm();
    }

    this.setupSessionColorPicker();
    this.showModal('sessionModal');
  }

  populateSessionForm(session) {
    document.getElementById('sessionNameInput').value = session.name;
    document.getElementById('sessionFingerprintProtection').checked = session.fingerprintProtection;
    document.getElementById('sessionUserAgent').value = session.userAgent || '';

    if (session.proxy && session.proxy.enabled) {
      document.getElementById('sessionEnableProxy').checked = true;
      document.getElementById('sessionProxyConfig').style.display = 'block';
      document.getElementById('sessionProxyType').value = session.proxy.type;
      document.getElementById('sessionProxyHost').value = session.proxy.host;
      document.getElementById('sessionProxyPort').value = session.proxy.port;
      document.getElementById('sessionProxyUsername').value = session.proxy.username || '';
      document.getElementById('sessionProxyPassword').value = session.proxy.password || '';
    }

    // Set selected color
    setTimeout(() => {
      const colorOption = document.querySelector(`[data-color="${session.color}"]`);
      if (colorOption) {
        document.querySelectorAll('.color-option').forEach(opt => opt.classList.remove('selected'));
        colorOption.classList.add('selected');
      }
    }, 100);
  }

  clearSessionForm() {
    document.getElementById('sessionNameInput').value = '';
    document.getElementById('sessionFingerprintProtection').checked = false;
    document.getElementById('sessionUserAgent').value = '';
    document.getElementById('sessionEnableProxy').checked = false;
    document.getElementById('sessionProxyConfig').style.display = 'none';
    document.getElementById('sessionProxyType').value = 'http';
    document.getElementById('sessionProxyHost').value = '';
    document.getElementById('sessionProxyPort').value = '';
    document.getElementById('sessionProxyUsername').value = '';
    document.getElementById('sessionProxyPassword').value = '';
  }

  setupSessionColorPicker() {
    const colorPicker = document.getElementById('sessionColorPicker');
    const colors = ['#4285f4', '#ea4335', '#fbbc04', '#34a853', '#ff6d01', '#9c27b0', '#00bcd4', '#795548'];
    
    colorPicker.innerHTML = '';
    colors.forEach(color => {
      const colorOption = document.createElement('div');
      colorOption.className = 'color-option';
      colorOption.style.backgroundColor = color;
      colorOption.dataset.color = color;
      colorOption.addEventListener('click', () => {
        document.querySelectorAll('.color-option').forEach(opt => opt.classList.remove('selected'));
        colorOption.classList.add('selected');
      });
      colorPicker.appendChild(colorOption);
    });

    // Select first color by default
    colorPicker.firstElementChild.classList.add('selected');
  }

  async saveSession() {
    const name = document.getElementById('sessionNameInput').value;
    const selectedColor = document.querySelector('.color-option.selected')?.dataset.color || '#4285f4';
    const fingerprintProtection = document.getElementById('sessionFingerprintProtection').checked;
    const userAgent = document.getElementById('sessionUserAgent').value;

    const config = {
      name,
      color: selectedColor,
      fingerprintProtection,
      userAgent: userAgent || null
    };

    if (document.getElementById('sessionEnableProxy').checked) {
      config.proxy = {
        enabled: true,
        type: document.getElementById('sessionProxyType').value,
        host: document.getElementById('sessionProxyHost').value,
        port: parseInt(document.getElementById('sessionProxyPort').value),
        username: document.getElementById('sessionProxyUsername').value || null,
        password: document.getElementById('sessionProxyPassword').value || null
      };
    }

    try {
      if (this.currentEditingSession) {
        await chrome.runtime.sendMessage({
          action: 'updateSession',
          sessionId: this.currentEditingSession,
          config
        });
      } else {
        await chrome.runtime.sendMessage({
          action: 'createSession',
          config
        });
      }

      this.hideModal('sessionModal');
      await this.loadSessions();
      this.updateSessionsGrid();
    } catch (error) {
      console.error('Failed to save session:', error);
      alert('Failed to save session. Please try again.');
    }
  }

  async editSession(sessionId) {
    this.showSessionModal(sessionId);
  }

  async deleteSession(sessionId) {
    if (!confirm('Are you sure you want to delete this session? All tabs in this session will be closed.')) {
      return;
    }

    try {
      await chrome.runtime.sendMessage({
        action: 'deleteSession',
        sessionId
      });

      await this.loadSessions();
      this.updateSessionsGrid();
    } catch (error) {
      console.error('Failed to delete session:', error);
      alert('Failed to delete session. Please try again.');
    }
  }

  showProxyModal() {
    this.showModal('proxyModal');
  }

  async saveProxy() {
    const proxy = {
      name: document.getElementById('proxyName').value,
      type: document.getElementById('proxyType').value,
      host: document.getElementById('proxyHost').value,
      port: parseInt(document.getElementById('proxyPort').value),
      username: document.getElementById('proxyUsername').value || null,
      password: document.getElementById('proxyPassword').value || null
    };

    this.proxies.push(proxy);
    await chrome.storage.local.set({ proxies: this.proxies });

    this.hideModal('proxyModal');
    document.getElementById('proxyForm').reset();
    this.updateProxyList();
  }

  async deleteProxy(index) {
    if (!confirm('Are you sure you want to delete this proxy configuration?')) {
      return;
    }

    this.proxies.splice(index, 1);
    await chrome.storage.local.set({ proxies: this.proxies });
    this.updateProxyList();
  }

  async testProxy() {
    const proxyConfig = {
      type: document.getElementById('proxyType').value,
      host: document.getElementById('proxyHost').value,
      port: parseInt(document.getElementById('proxyPort').value),
      username: document.getElementById('proxyUsername').value || null,
      password: document.getElementById('proxyPassword').value || null
    };

    try {
      const testBtn = document.getElementById('testProxyBtn');
      testBtn.textContent = 'Testing...';
      testBtn.disabled = true;

      // Test proxy connection (simplified)
      const response = await fetch('https://httpbin.org/ip', {
        method: 'GET'
      });

      if (response.ok) {
        alert('Proxy connection test successful!');
      } else {
        alert('Proxy connection test failed.');
      }
    } catch (error) {
      alert('Proxy connection test failed: ' + error.message);
    } finally {
      const testBtn = document.getElementById('testProxyBtn');
      testBtn.textContent = 'Test Connection';
      testBtn.disabled = false;
    }
  }

  async saveSettings() {
    // Collect settings from form
    this.settings = {
      autoSwitchSession: document.getElementById('autoSwitchSession').checked,
      showSessionIndicator: document.getElementById('showSessionIndicator').checked,
      enableNotifications: document.getElementById('enableNotifications').checked,
      defaultSessionName: document.getElementById('defaultSessionName').value,
      defaultFingerprintProtection: document.getElementById('defaultFingerprintProtection').value,
      enableGlobalProxy: document.getElementById('enableGlobalProxy').checked,
      protectCanvas: document.getElementById('protectCanvas').checked,
      protectWebGL: document.getElementById('protectWebGL').checked,
      protectAudio: document.getElementById('protectAudio').checked,
      blockWebRTC: document.getElementById('blockWebRTC').checked,
      userAgentMode: document.getElementById('userAgentMode').value,
      customUserAgent: document.getElementById('customUserAgent').value,
      maxSessions: parseInt(document.getElementById('maxSessions').value),
      sessionTimeout: parseInt(document.getElementById('sessionTimeout').value),
      enableDebugMode: document.getElementById('enableDebugMode').checked,
      clearDataOnClose: document.getElementById('clearDataOnClose').checked,
      autoBackup: document.getElementById('autoBackup').checked
    };

    try {
      await chrome.storage.local.set({ settings: this.settings });
      
      // Show success message
      const saveBtn = document.getElementById('saveBtn');
      const originalText = saveBtn.textContent;
      saveBtn.textContent = 'Saved!';
      saveBtn.style.background = '#34a853';
      
      setTimeout(() => {
        saveBtn.textContent = originalText;
        saveBtn.style.background = '';
      }, 2000);
    } catch (error) {
      console.error('Failed to save settings:', error);
      alert('Failed to save settings. Please try again.');
    }
  }

  async clearAllData() {
    if (!confirm('Are you sure you want to clear all session data? This action cannot be undone.')) {
      return;
    }

    try {
      await chrome.storage.local.clear();
      await chrome.runtime.sendMessage({ action: 'clearAllData' });
      
      alert('All session data has been cleared.');
      location.reload();
    } catch (error) {
      console.error('Failed to clear data:', error);
      alert('Failed to clear data. Please try again.');
    }
  }

  async createBackup() {
    try {
      const backupData = {
        sessions: this.sessions,
        settings: this.settings,
        proxies: this.proxies,
        timestamp: Date.now(),
        version: '1.0.0'
      };

      const blob = new Blob([JSON.stringify(backupData, null, 2)], {
        type: 'application/json'
      });

      const url = URL.createObjectURL(blob);
      const a = document.createElement('a');
      a.href = url;
      a.download = `sessionbox-backup-${new Date().toISOString().split('T')[0]}.json`;
      a.click();

      URL.revokeObjectURL(url);
    } catch (error) {
      console.error('Failed to create backup:', error);
      alert('Failed to create backup. Please try again.');
    }
  }

  async restoreBackup() {
    const input = document.createElement('input');
    input.type = 'file';
    input.accept = '.json';

    input.onchange = async (e) => {
      const file = e.target.files[0];
      if (!file) return;

      try {
        const content = await file.text();
        const backupData = JSON.parse(content);

        if (!backupData.sessions || !backupData.settings) {
          throw new Error('Invalid backup file format');
        }

        await chrome.storage.local.set({
          settings: backupData.settings,
          proxies: backupData.proxies || []
        });

        // Restore sessions
        for (const session of backupData.sessions) {
          await chrome.runtime.sendMessage({
            action: 'createSession',
            config: session
          });
        }

        alert('Backup restored successfully. Please refresh the page.');
        location.reload();
      } catch (error) {
        console.error('Failed to restore backup:', error);
        alert('Failed to restore backup. Please check the file format.');
      }
    };

    input.click();
  }

  async importSessions() {
    const input = document.createElement('input');
    input.type = 'file';
    input.accept = '.json';

    input.onchange = async (e) => {
      const file = e.target.files[0];
      if (!file) return;

      try {
        const content = await file.text();
        const sessions = JSON.parse(content);

        for (const sessionData of sessions) {
          await chrome.runtime.sendMessage({
            action: 'createSession',
            config: sessionData
          });
        }

        await this.loadSessions();
        this.updateSessionsGrid();
        alert(`Successfully imported ${sessions.length} sessions.`);
      } catch (error) {
        console.error('Failed to import sessions:', error);
        alert('Failed to import sessions. Please check the file format.');
      }
    };

    input.click();
  }

  async exportSessions() {
    try {
      const exportData = this.sessions.map(session => ({
        name: session.name,
        color: session.color,
        proxy: session.proxy,
        userAgent: session.userAgent,
        fingerprintProtection: session.fingerprintProtection
      }));

      const blob = new Blob([JSON.stringify(exportData, null, 2)], {
        type: 'application/json'
      });

      const url = URL.createObjectURL(blob);
      const a = document.createElement('a');
      a.href = url;
      a.download = `sessionbox-sessions-${new Date().toISOString().split('T')[0]}.json`;
      a.click();

      URL.revokeObjectURL(url);
    } catch (error) {
      console.error('Failed to export sessions:', error);
      alert('Failed to export sessions. Please try again.');
    }
  }

  formatDate(timestamp) {
    const date = new Date(timestamp);
    const now = new Date();
    const diff = now - date;

    if (diff < 60000) return 'Now';
    if (diff < 3600000) return `${Math.floor(diff / 60000)}m`;
    if (diff < 86400000) return `${Math.floor(diff / 3600000)}h`;
    return `${Math.floor(diff / 86400000)}d`;
  }

  showModal(modalId) {
    document.getElementById(modalId).classList.add('show');
  }

  hideModal(modalId) {
    document.getElementById(modalId).classList.remove('show');
  }
}

// Initialize options manager
let optionsManager;
document.addEventListener('DOMContentLoaded', () => {
  optionsManager = new OptionsManager();
}); 